package com.bifang.service.impl;

import com.alibaba.fastjson.JSON;
import com.bifang.entity.Rst;
import com.bifang.service.CalService;
import com.bifang.utils.MathUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class CalServiceImpl implements CalService {
    private final String filename = "C:/Users/XiaoRan/Desktop/del/data.dat";
    @Override
    public String cal(String s) {
        String rst = "";
        boolean flag = false;
        String regex = "(?<=op)|(?=op)".replace("op", "[-+*/()]");
        String[] split = s.split(regex);
        try{
            List<String> strings = MathUtil.MiddleToEndExpress(Arrays.asList(split));
            rst = String.valueOf(MathUtil.endCalculator(strings));
        } catch(Exception e){
            rst = "ERROR";
            flag = true;
            e.printStackTrace();
        }
        if(!flag){
            // 存储
            save(s, rst);
        }
        return rst;
    }

    @Override
    public List<Rst> getHistory() {
        ArrayList<Rst> rsts = new ArrayList<>();
        try {
            String data = FileUtils.readFileToString(new File(filename), StandardCharsets.UTF_8);
            String[] items = data.split("\\|\\|");
            for (String item : items) {
                String[] val = item.split(";");
                Rst rst = new Rst(val[0], val[1], val[2]);
                rsts.add(rst);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return rsts;
    }


    public void save(String s, String rst){

       String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
       // 存储位置默认 windows 为 C:\Users\XiaoRan\Desktop\del

        File file = new File(filename);
        Rst obj = new Rst(s, rst, date);
        if(file.exists()){
            try {
                String  data = FileUtils.readFileToString(new File(filename), StandardCharsets.UTF_8);
                FileUtils.write(file, data+"||"+obj.toString(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                FileUtils.write(file, obj.toString(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
